﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

[ExecuteInEditMode]
[AddComponentMenu("UI/Behavior/ColorIndex")]
public class UIColorIndex : MonoBehaviour, IUIIndex
{
    public Color[] colors;

    public enum TYPE
    {
        UIElement,
        Shadow,
        Event,
    }


    public TYPE type = TYPE.UIElement;


    [SerializeField]
    private int _index;
    public int index
    {
        get
        {
            return _index;
        }
        set
        {
            if (value > colors.Length - 1) value = colors.Length - 1;
            if (value < 0) value = 0;
            UpdateFromIndex(value);
            _index = value;
        }
    }


    public ColorIndexEvent colorEvent;

    [HideInInspector]
    public Color curColor = new Color(1, 1, 1, 1);

    [Tooltip("是否将颜色应用给所有子对象？")]
    public bool forEachChild = false;


    [System.Serializable]
    public class ColorIndexEvent : UnityEvent<Color>
    {

    }

#if UNITY_EDITOR
    bool _dirty = false;
    private void OnValidate()
    {
        if (colors == null || colors.Length <= 0) return;
        if (_index > colors.Length - 1) _index = colors.Length - 1;
        if (_index < 0) _index = 0;
        _dirty = true;
    }

    private void Update()
    {
        if (_dirty)
        {
            _dirty = false;
            UpdateFromIndex(_index);
        }
    }
#endif

    public Color GetColor(int index)
    {
        index = Mathf.Clamp(index, 0, colors.Length);
        return colors[index];
    }

    private void UpdateFromIndex(int value)
    {
        var color = GetColor(value);
        if (color == null) return;
        switch (type)
        {
            case TYPE.Shadow:
                if (forEachChild)
                {
                    var shadows = GetComponentsInChildren<Shadow>();
                    foreach (var shadow in shadows)
                    {
                        shadow.effectColor = color;
                    }

                }
                else
                {
                    var shadow = GetComponent<Shadow>();
                    if (shadow != null) shadow.effectColor = color;
                }
                break;
            case TYPE.UIElement:
                if (forEachChild)
                {
                    var cs = GetComponentsInChildren<UnityEngine.UI.Graphic>();
                    foreach (var c in cs)
                    {
                        c.color = color;
                    }
                }
                else
                {
                    var graphic = GetComponent<UnityEngine.UI.Graphic>();
                    if (graphic != null) graphic.color = color;
                }

                break;
            case TYPE.Event:
                curColor = color;
                colorEvent.Invoke(curColor);
                break;
        }

    }


}
